const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const db = require('./db');
const path = require('path');

const app = express();

// 添加静态文件服务
app.use(express.static(path.join(__dirname)));

app.use(bodyParser.json());
app.use(cors());

// 添加路由处理首页
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'test.html'));
});

// 配置项
const JWT_SECRET = 'your_jwt_secret';
const CODE_EXPIRE = 5 * 60 * 1000; // 5分钟
const ACCESS_TOKEN_EXPIRE = '15m';
const REFRESH_TOKEN_EXPIRE = '7d';

// 统一响应格式
const successResponse = (data = null, message = '操作成功') => ({
  code: 200,
  message,
  data
});
const errorResponse = (message = '操作失败', code = 500) => ({
  code,
  message,
  data: null
});

// =========== 认证相关API ===========
// 发送验证码
app.post('/api/send-code', async (req, res) => {
  try {
    const { phone } = req.body;

    if (!phone) {
      return res.json(errorResponse('手机号不能为空', 400));
    }

    const code = Math.floor(100000 + Math.random() * 900000);
    const expires = Date.now() + CODE_EXPIRE;

    // 存储验证码到数据库
    await db.query(
      'INSERT INTO verification_codes (phone, code, expires) VALUES (?, ?, ?)',
      [phone, code.toString(), expires]
    );

    // 模拟发送短信
    console.log(`发送验证码到 ${phone}: ${code}`);
    res.json(successResponse({
      captcha: code,
      expiresIn: CODE_EXPIRE / 1000
    }, '验证码已发送'));
  } catch (error) {
    console.error('发送验证码错误:', error);
    res.json(errorResponse('发送验证码失败'));
  }
});

// 登录验证
app.post('/api/login', async (req, res) => {
  try {
    const { phone, code } = req.body;

    if (!phone || !code) {
      return res.json(errorResponse('手机号和验证码不能为空', 400));
    }

    // 从数据库获取验证码
    const [verificationCode] = await db.query(
      'SELECT * FROM verification_codes WHERE phone = ? ORDER BY created_at DESC LIMIT 1',
      [phone]
    );

    if (!verificationCode || verificationCode.code !== code) {
      return res.json(errorResponse('验证码错误', 401));
    }

    if (Date.now() > verificationCode.expires) {
      return res.json(errorResponse('验证码已过期', 401));
    }

    // 生成令牌
    const accessToken = jwt.sign({ phone }, JWT_SECRET, { expiresIn: ACCESS_TOKEN_EXPIRE });
    const refreshToken = uuidv4();
    const refreshTokenExpires = Date.now() + 7 * 24 * 60 * 60 * 1000;

    // 存储refreshToken到数据库
    await db.query(
      'INSERT INTO refresh_tokens (token, phone, expires) VALUES (?, ?, ?)',
      [refreshToken, phone, refreshTokenExpires]
    );

    // 确保用户存在
    await db.query(
      'INSERT IGNORE INTO users (phone) VALUES (?)',
      [phone]
    );

    res.json(successResponse({ accessToken, refreshToken }));
  } catch (error) {
    console.error('登录错误:', error);
    res.json(errorResponse('登录失败'));
  }
});

// 刷新令牌
app.post('/api/refresh-token', async (req, res) => {
  try {
    const { refreshToken } = req.body;

    if (!refreshToken) {
      return res.json(errorResponse('刷新令牌不能为空', 400));
    }

    // 从数据库获取refreshToken
    const [tokenData] = await db.query(
      'SELECT * FROM refresh_tokens WHERE token = ?',
      [refreshToken]
    );

    if (!tokenData || Date.now() > tokenData.expires) {
      return res.json(errorResponse('无效的refresh token', 401));
    }

    // 生成新accessToken
    const newAccessToken = jwt.sign({ phone: tokenData.phone }, JWT_SECRET, {
      expiresIn: ACCESS_TOKEN_EXPIRE
    });

    res.json(successResponse({ accessToken: newAccessToken }));
  } catch (error) {
    console.error('刷新令牌错误:', error);
    res.json(errorResponse('刷新令牌失败'));
  }
});

// =========== 工作台API ===========
// 获取发布数据
app.get('/api/workbench/publish-data', async (req, res) => {
  try {
    // 从数据库获取发布数据
    let [publishData] = await db.query('SELECT * FROM publish_data LIMIT 1');
    
    if (!publishData) {
      // 如果没有数据，初始化一条记录
      await db.query(
        'INSERT INTO publish_data (downloads, created, collected) VALUES (0, 6, 0)'
      );
      publishData = { downloads: 0, created: 6, collected: 0 };
    }

    res.json(successResponse(publishData));
  } catch (error) {
    console.error('获取发布数据错误:', error);
    res.json(errorResponse('获取发布数据失败'));
  }
});

// 获取工作列表
app.get('/api/workbench/work-list', async (req, res) => {
  try {
    // 从数据库获取工作列表
    const workList = await db.query('SELECT * FROM work_items ORDER BY created_at DESC');
    res.json(successResponse(workList));
  } catch (error) {
    console.error('获取工作列表错误:', error);
    res.json(errorResponse('获取工作列表失败'));
  }
});

// =========== 模板相关API ===========
// 获取模板列表
app.get('/api/templates', async (req, res) => {
  try {
    // 获取所有模板
    const templates = await db.query('SELECT * FROM templates ORDER BY id');
    
    // 获取所有模板图片
    const templateImages = await db.query('SELECT * FROM template_images ORDER BY template_id, sort_order');
    
    // 组织数据结构
    const templatesWithImages = templates.map(template => {
      const images = templateImages
        .filter(img => img.template_id === template.id)
        .map(img => img.image_url);
      
      return {
        ...template,
        images: images.length > 0 ? images : undefined
      };
    });

    res.json(successResponse(templatesWithImages));
  } catch (error) {
    console.error('获取模板列表错误:', error);
    res.json(errorResponse('获取模板列表失败'));
  }
});

// 启动服务器
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  console.log('可用的API端点：');
  console.log('认证相关：');
  console.log(`- 发送验证码: POST http://localhost:${PORT}/api/send-code`);
  console.log(`- 登录: POST http://localhost:${PORT}/api/login`);
  console.log(`- 刷新令牌: POST http://localhost:${PORT}/api/refresh-token`);
  console.log('工作台相关：');
  console.log(`- 获取发布数据: GET http://localhost:${PORT}/api/workbench/publish-data`);
  console.log(`- 获取工作列表: GET http://localhost:${PORT}/api/workbench/work-list`);
  console.log('模板相关：');
  console.log(`- 获取模板列表: GET http://localhost:${PORT}/api/templates`);
});